package com.neo.v1;

import com.neo.util.CommonUtil;

import java.util.ArrayList;
import java.util.List;

import static com.neo.util.SystemUtil.printMsg;

/**
 * 1.4.4 演示线程的整个生命周期中 各状态的流转
 */
public class V144ThreadLifeCycle {
    private static final long MAX_TURN = 3;

    private static int threadSeqNumber = 0;

    private static List<Thread> threadList = new ArrayList<>();

    private static void printThreadStatus(){
        for (Thread thread:threadList){
            printMsg(String.format("[%d]%s 状态为: %s", thread.getId(),thread.getName(),thread.getState()));
        }
    }

    private static void addStatusThread(Thread thread){
        threadList.add(thread);
    }

    static class StatusDemoThread extends Thread{
        public StatusDemoThread(){
            super("statusPrintThread" + (++threadSeqNumber));
            addStatusThread(this);
        }
        @Override
        public void run(){
            printMsg(this.getName()  + " StatusDemoThread 状态为: " + getState());
            for (int i = 0; i < MAX_TURN; i++) {
                try {
                    sleep(500);
                    printThreadStatus();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            printMsg(this.getName() + "运行结束!!!");
        }

    }

    public static void main(String[] args){
        addStatusThread(Thread.currentThread());

        for (int i = 0; i < 3; i++) {
            Thread thread = new StatusDemoThread();
            printMsg(thread.getName() + " before状态为: " + thread.getState());
            thread.start();
            CommonUtil.sleepMilliSeconds((i+1)*100);
            printMsg(thread.getName() + " after状态为: " + thread.getState());
        }
        while(true){

        }
    }
}
